<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <!-- <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="日志内容"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="createTime" label="操作时间">
          <el-date-picker
            v-model="queryParams.createTime"
            :editable="false"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div> -->
    <el-card shadow="hover" class="data-table">
      <el-table
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        class="data-table__content"
        style="width: 100%"
      >
        <el-table-column
          v-for="(ruleColumn, index) in tableRuleColumns"
          :key="ruleColumn.key || index"
          :label="ruleColumn.label"
          :prop="ruleColumn.key"
          :align="ruleColumn.align || 'left'"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span>{{ formatCellValue(row, ruleColumn) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <offset-pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:offset="queryParams.offset"
        v-model:limit="queryParams.limit"
        @pagination="fetchData"
      />
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import { useHmiConfigStore } from "@/store";
import { useCommonApiStore } from "@/store/modules/common-hmi-data.store";
import OffsetPagination from "@/components/Pagination/OffsetPagination.vue";
import { formatOnlySelectTableData, formatCellValue } from "@/utils/hmi-data-table";
import type { TableHeaderRule, ColumnRule } from "@/api/hmi/config.api";
import type { CommonHmiDataOffsetPageQuery } from "@/api/hmi/common-hmi-data.api";

defineOptions({
  name: "OnlySelect",
  inheritAttrs: false,
});

const route = useRoute();
const queryFormRef = ref();
const hmiConfigStore = useHmiConfigStore();
const commonApiStore = useCommonApiStore();

const loading = ref(false);
const total = ref(0);
const tableData = ref<Record<string, any>[]>([]);
const tableHeaders = ref<string[]>([]);
const tableRuleColumns = ref<ColumnRule[]>([]);
const curTableRule = ref<TableHeaderRule | null>(null);

const queryParams = reactive<CommonHmiDataOffsetPageQuery>({
  offset: 0,
  limit: 10,
  keywords: "",
  createTime: ["", ""],
});

const apiPath = ref<string>("");
// const apiPath = computed(() => {
//   // 兼容 meta.params.api 可能为字符串或对象
//   const metaApi = route?.meta?.params?.api;
//   if (typeof metaApi === "string") return metaApi;
//   if (metaApi && typeof metaApi === "object" && "value" in metaApi) return metaApi.value;
//   return "";
// });

async function fetchData() {
  if (!apiPath.value) return;
  loading.value = true;
  try {
    const data = await commonApiStore.fetchList(apiPath.value, { ...queryParams });
    total.value = +data.total;
    const { tableHeaders: newTableHeaders, tableData: newTableData } = formatOnlySelectTableData(
      data.list,
      tableRuleColumns.value
    );
    tableHeaders.value = newTableHeaders;
    tableData.value = newTableData;
  } catch (error) {
    console.error("获取数据失败:", error);
  } finally {
    loading.value = false;
  }
}

function handleQuery() {
  queryParams.offset = 0;
  fetchData();
}

function handleResetQuery() {
  queryFormRef.value?.resetFields();
  queryParams.offset = 0;
  queryParams.limit = 10;
  queryParams.keywords = "";
  queryParams.createTime = ["", ""];
  fetchData();
}

function updateTableRuleAndFetchData(api: string) {
  // const headerRule = hmiConfigStore.getTableHeaderRuleByUri(api);
  const headerRule = hmiConfigStore.getTableHeaderRuleByPath(route.path);
  if (headerRule) {
    curTableRule.value = headerRule;
    tableRuleColumns.value =
      headerRule.columns?.slice().sort((a, b) => (a.index ?? 0) - (b.index ?? 0)) || [];
  } else {
    curTableRule.value = null;
    tableRuleColumns.value = [];
  }
  fetchData();
}
// apiPath 根据 route?.meta?.params?.api; 计算得到
// 监听 apiPath 变化，只有当前页面激活时，才执行 updateTableRuleAndFetchData 函数，进行更新
const isPageActive = ref(true); // 添加页面激活状态标识

onActivated(() => {
  isPageActive.value = true;
});

onDeactivated(() => {
  isPageActive.value = false;
});

watch(
  () => apiPath.value,
  (oldApi, newApi) => {
    // console.log("only-select oldApi", oldApi, "newApi", newApi, "isPageActive", isPageActive.value);
    if (newApi && isPageActive.value) {
      // console.log("only-select updateTableRuleAndFetchData", newApi);
      updateTableRuleAndFetchData(newApi);
    }
  }
  // { immediate: true }
);

onMounted(async () => {
  try {
    apiPath.value = route?.meta?.params?.api || "";
    await hmiConfigStore.initHmiConfig();
    if (apiPath.value) {
      updateTableRuleAndFetchData(apiPath.value);
    }
  } catch (error) {
    console.error("初始化配置失败:", error);
  }
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.search-container {
  margin-bottom: 16px;
}
/* .data-table {
  margin-top: 0;
} */
</style>
